<%+cbi/valueheader%>
<div id="application_http_headers">
<%
	local vals = self:cfgvalue(section) or {}
	for i=1, #vals + 1 do
		local val = vals[i]
		if (val and #val > 0) or (i == 1) then
%>

	<input class="http_headers" value="<%=pcdata(val)%>"  type="hidden"<%=
		attr("id", cbid .. "." .. i) .. attr("name", cbid) .. ifattr(self.size, "size") ..
		ifattr(i == 1 and self.placeholder, "placeholder", self.placeholder)
	%> /><br />
<% end end %>
</div>
<script type="text/javascript">
	var NextID = <%=#vals + 1%>; 
	function hname_c(a, i){
		var item = $("#cbid\\.lorasrv\\.<%=section%>\\.http_headers\\."+i);
		if( $(a).next().next().val().length > 0 && $(a).length > 0)
			item.val($(a).val() + ": " + $(a).next().next().val())
		else
			item.val("");
	}
	function hvalue_c(a, i){
		var item = $("#cbid\\.lorasrv\\.<%=section%>\\.http_headers\\."+i);
		if( $(a).prev().prev().val().length > 0 && $(a).val().length > 0)
			item.val($(a).prev().prev().val() + ": " + $(a).val())
		else
			item.val("");
	}
	function remove_header(item){
		$(item).prev().remove();
		$(item).prev().remove();
		$(item).prev().remove();
		$(item).next().remove();
		$(item).next().remove();
		$(item).remove();
	}
	function add_header(){
		console.log($(".http_headers").length)
		var last = $(".http_headers").last();
		last.prev().remove();
		last.before("<img src='/luci-static/resources/cbi/remove.gif' class='cbi-image-button' onclick='remove_header(this)' class='_rm_btn' />")
		$("#application_http_headers").append("<input type='text' placeholder='Header Name' onchange='hname_c(this,"+(NextID)+")' ><span>:</span><input placeholder='Header Value' type='text' onchange='hvalue_c(this,"+NextID+")'><img src='/luci-static/resources/cbi/add.gif' class='cbi-image-button' onclick='add_header()' /><input class='http_headers' value='' type='hidden' id='<%=cbid%>." +NextID+"' name=<%=cbid%> /><br />");
		NextID++;
	}
	$(document).ready(function(){
		$(".http_headers").each(function(i,v){
			var header = $(v).val().split(":");
			$(v).before("<input type='text' placeholder='Header Name' value='"+(header[0]?header[0]:"")+"' onchange='hname_c(this, "+(i+1)+")' /><span>:</span><input placeholder='Header Value' type='text' value='"+(header[1]?header[1]:"")+"' onchange='hvalue_c(this, "+(i+1)+")' />");
			if( i == ($(".http_headers").length - 1)){
				$(v).before("<img class='_add_btn' src='/luci-static/resources/cbi/add.gif' class='cbi-image-button' onclick='add_header()' />");
			}
			else{
				$(v).before("<img src='/luci-static/resources/cbi/remove.gif' class='cbi-image-button' onclick='remove_header(this)' class='_rm_btn' />");
			}

		})
	});
</script>
<%+cbi/valuefooter%>
